package vn.candyapp.qlct;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import vn.candyapp.qlct.database.DBAdapter;
import vn.candyapp.qlct.database.model.AccountList;
import vn.candyapp.qlct.database.model.CategoryList;
import vn.candyapp.qlct.database.model.PaymentStatusList;
import vn.candyapp.qlct.database.model.Transaction;
import vn.candyapp.qlct.database.model.TransactionType;
import vn.candyapp.qlct.database.model.TransactionTypeList;
import vn.candyapp.qlct.utils.DateTimeUtil;
import vn.candyapp.qlct.utils.DialogUtils;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class AddTransactionActivity extends ActionBarActivity {

	private Spinner spinCategory;
	private Spinner spinTransaction, spinPaymentStatus, spinAccount;
	private DBAdapter dbAdapter;
	private CategoryList categoriesList;
	private TransactionTypeList transactionTypeList;
	private PaymentStatusList paymentStatusList;
	private AccountList accountList;
	private ArrayAdapter<String> paymentStatusAdapter, accountAdapter;
	private Button btnDate, btnTime, btnNow, btnSave, btnSaveAndBack;
	private Date currentDate = Calendar.getInstance().getTime();
	private Calendar mCalendar = Calendar.getInstance();
	private EditText editAmount, editReason;
	private ArrayAdapter<String> catAdapter;
	private ArrayAdapter<String> tranAdater;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dbAdapter = new DBAdapter(this);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		setContentView(R.layout.activity_add_transaction);
		initWidgets();
		loadData();
		addEvent();
	}
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			spinCategory.setAdapter(catAdapter);
			spinTransaction.setAdapter(tranAdater);
			spinPaymentStatus.setAdapter(paymentStatusAdapter);
			spinAccount.setAdapter(accountAdapter);
		}
		
	};
	
	private void loadData() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				transactionTypeList = dbAdapter.getAllTransactionType();
				categoriesList = dbAdapter.getAllCategories(1);
				paymentStatusList = dbAdapter.getPaymentStatus();
				accountList = dbAdapter.getAccounts();
				
				// khai bao adapter cho spinner category
				catAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, categoriesList.getCatNames());
				catAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
				
				// khai bao adapter cho spinner transaction type
				tranAdater = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, transactionTypeList.getTransactionTypeName());
				tranAdater.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
				
				
				// khai bao adapter cho spinner payment status
				paymentStatusAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, paymentStatusList.getPaymentStatusName());
				paymentStatusAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
				
				
				// khai bao adapter cho spinner account (loai tai khoan)
				accountAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, accountList.getAccountNames());
				accountAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
				
				Message msg = mHandler.obtainMessage();
				mHandler.sendMessage(msg);
			}
		}).start();
		
	}
	
	@Override
	public boolean onSupportNavigateUp() {
		finish();
		return super.onSupportNavigateUp();
	}

	private void initWidgets() {
		spinTransaction = (Spinner) findViewById(R.id.spinTransaction);
		spinCategory = (Spinner) findViewById(R.id.spinCategory);
		spinPaymentStatus = (Spinner) findViewById(R.id.spinPaymentStatus);
		spinAccount = (Spinner) findViewById(R.id.spinAccount);
		btnDate = (Button) findViewById(R.id.btnDate);
		btnTime = (Button) findViewById(R.id.btnTime);
		btnNow = (Button) findViewById(R.id.btnNow);
		btnDate.setText(DateTimeUtil.getNgayThangNam(currentDate));
		btnTime.setText(DateTimeUtil.getGio(currentDate, "HH:mm"));
		btnSave = (Button) findViewById(R.id.btnSave);
		btnSaveAndBack = (Button) findViewById(R.id.btnSaveNBack);
		editAmount = (EditText) findViewById(R.id.editAmount);
		editReason = (EditText) findViewById(R.id.editReason);
	}
	
	private void addEvent() {
		spinTransaction.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String typeName = transactionTypeList.getTransactionTypeAtPosition(position).getTypeName();
				int transactionTypeId = "expense".equals(typeName) ? 1 : 2;
				categoriesList = dbAdapter.getAllCategories(transactionTypeId);
				// khai bao adapter cho spinner category
				ArrayAdapter<String> catAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, categoriesList.getCatNames());
				catAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
				spinCategory.setAdapter(catAdapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
		btnNow.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				currentDate = Calendar.getInstance().getTime();
				btnDate.setText(DateTimeUtil.getNgayThangNam(currentDate));
				btnTime.setText(DateTimeUtil.getGio(currentDate, "HH:mm"));
			}
		});
		
		btnTime.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				TimePickerDialog dialog = new TimePickerDialog(AddTransactionActivity.this, new TimePickerDialog.OnTimeSetListener() {
					
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
						mCalendar.set(Calendar.MINUTE, minute);
						currentDate = mCalendar.getTime();
						btnTime.setText(DateTimeUtil.getGio(currentDate, "HH:mm"));
					}
				}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
				dialog.setTitle(getString(R.string.choose_transaction_time));
				dialog.show();
			}
		});
		btnDate.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DatePickerDialog dialog = new DatePickerDialog(AddTransactionActivity.this, new DatePickerDialog.OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						mCalendar.set(Calendar.YEAR, year);
						mCalendar.set(Calendar.MONTH, monthOfYear);
						mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
						currentDate = mCalendar.getTime();
						btnDate.setText(DateTimeUtil.getNgayThangNam(currentDate));
					}
				}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
				dialog.setTitle(getString(R.string.choose_transaction_day));
				dialog.show();
			}
		});
		
		btnSave.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if ("".equals(editAmount.getText()+"")) {
					DialogUtils.showMessage(AddTransactionActivity.this, getString(R.string.show_msg_must_fill_amount));
				} else {
					// TODO them vao csdl
					addToDatabase();
				}
			}
		});
		btnSaveAndBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if ("".equals(editAmount.getText()+"")) {
					DialogUtils.showMessage(AddTransactionActivity.this, getString(R.string.show_msg_must_fill_amount));
				} else {
					// TODO them vao csdl
					addToDatabase();
					finish();
				}
			}
		});
	}
	
	private void addToDatabase() {
		String reason = editReason.getText().toString();
		TransactionType transactionType = transactionTypeList.getTransactionTypeAtPosition(spinTransaction.getSelectedItemPosition());
		int transactionTypeId = transactionType.getId();
		float amount = Float.parseFloat(editAmount.getText().toString());
		int catId = categoriesList.getCategoryAtPosition(spinCategory.getSelectedItemPosition()).getId();
		int paymentStatusId = paymentStatusList.getPaymentStatusAtPosition(spinPaymentStatus.getSelectedItemPosition()).getId();
		int accountId = accountList.getAccountAtPosition(spinAccount.getSelectedItemPosition()).getId();
		
		Transaction t = new Transaction();
		t.setAccountId(accountId);
		t.setCategoryId(catId);
		t.setDescription(reason);
		t.setAmount(amount);
		t.setPaymentStatus(paymentStatusId);
		t.setTransactionType(transactionTypeId);
		SimpleDateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		t.setCreatedDate(dfm.format(currentDate));
		t.setTransactionTypeName(transactionType.getTypeName());
		
		long affectedRowId = dbAdapter.addNewTransaction(t);
		String msg = affectedRowId == -1 ? getString(R.string.insert_transaction_failed) : getString(R.string.insert_transaction_successfully);
		
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onBackPressed() {
		setResult(RESULT_OK, new Intent());
		super.onBackPressed();
	}
}
